package com.googlecode.intellimars.mrsp.tableview;

import com.googlecode.intellimars.mrsp.MaveRepoSearchPlugin;
import com.googlecode.intellimars.mrsp.MavenTagMaker;
import com.googlecode.intellimars.mrsp.SCOPE;
import com.googlecode.intellimars.mrsp.tableview.column.ArtifactId;
import com.googlecode.intellimars.mrsp.tableview.column.GroupId;
import com.googlecode.intellimars.mrsp.tableview.column.RepositoryUrl;
import com.googlecode.intellimars.mrsp.tableview.column.Type;
import com.googlecode.intellimars.mrsp.tableview.column.Version;
import com.intellij.ide.BrowserUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.ui.table.TableView;
import com.intellij.util.ui.ListTableModel;
import jp.sourceforge.mrsp.model.Artifact;
import jp.sourceforge.mrsp.service.RepoSearchService;
import jp.sourceforge.mrsp.service.RepoSearchServiceException;
import jp.sourceforge.mrsp.service.RepoSearchServiceImpl;

import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.List;

public class ArtifactListTableView extends TableView<Artifact> {
    private static Logger LOG = Logger.getInstance("mrsp");

    private JPopupMenu popupMenu = new JPopupMenu();
    private JMenuItem copyClipBoard = new JMenuItem("Copy <dependency>Tag");
    private JMenu copyClipBoard_scope = new JMenu("Copy <dependency>Tag + <scope>Tag");
    private JMenuItem copyClipBoard_repo = new JMenuItem("Copy <repository>Tag");
    private JMenuItem browseUrl = new JMenuItem("Browse Repository URL");

    private ListTableModel<Artifact> tableModel;
    private RepoSearchService searchService;

    public ArtifactListTableView() {
        setRowSelectionAllowed(true);
        setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        getTableHeader().setReorderingAllowed(false);

        copyClipBoard.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                _actionCopyClipBoard("", false);
            }
        });
        popupMenu.add(copyClipBoard);

        for (SCOPE scope : SCOPE.values()) {
            JMenuItem scopeMenu = new JMenuItem(scope.toString());
            scopeMenu.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    _actionCopyClipBoard(e.getActionCommand(), false);
                }
            });
            copyClipBoard_scope.add(scopeMenu);
        }
        popupMenu.add(copyClipBoard_scope);

        copyClipBoard_repo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                _actionCopyClipBoard("", true);
            }
        });
        popupMenu.add(copyClipBoard_repo);

        popupMenu.add(new JSeparator());

        browseUrl.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int selectRow = getSelectedRow();
                Artifact artifact = (Artifact) tableModel.getItem(selectRow);
                BrowserUtil.launchBrowser(artifact.getRepoUrl());
            }
        });
        popupMenu.add(browseUrl);

        setComponentPopupMenu(popupMenu);

        addMouseListener(new MouseInputAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    _actionCopyClipBoard("", false);
                }
            }
        });

        setModel(tableModel = new ListTableModel<Artifact>(
                new GroupId(),
                new ArtifactId(),
                new Version(),
                new Type(),
                new RepositoryUrl()
        ));
        searchService = new RepoSearchServiceImpl();
    }

    public void search(String keyword, String type) {
        try {
            List<Artifact> artifacts = searchService.searchArtifactByKeywordType(keyword, type);
            if (artifacts.size() == 0) {
                JOptionPane.showMessageDialog(this, "The Artifacts was not found.",
                                              MaveRepoSearchPlugin.TOOL_WINDOW_ID,
                                              JOptionPane.WARNING_MESSAGE);
            }
            tableModel.setItems(artifacts);
            tableModel.sortByColumn(0);
        }
        catch (RepoSearchServiceException e) {
            LOG.error(e);
            JOptionPane.showMessageDialog(this, "The unexpected error happened!!",
                                          MaveRepoSearchPlugin.TOOL_WINDOW_ID,
                                          JOptionPane.ERROR_MESSAGE);
        }
    }

    private void _actionCopyClipBoard(String scope, boolean isRepo) {
        int selectRow = getSelectedRow();
        Artifact artifact = (Artifact) tableModel.getItem(selectRow);
        CopyPasteManager copyPasteManager = CopyPasteManager.getInstance();
        copyPasteManager.setContents(new StringSelection(
                MavenTagMaker.create(artifact, scope, isRepo)
        ));
    }

    public String getToolTipText(MouseEvent event) {
        Point p = event.getPoint();
        int rowIndex = rowAtPoint(p);

        int columnIndex = columnAtPoint(p);
        int modelColumnIndex = convertColumnIndexToModel(columnIndex);
        return (String) tableModel.getValueAt(rowIndex, modelColumnIndex);
    }

    protected void onHeaderClicked(int column) {
        super.onHeaderClicked(column);
        getTableHeader().repaint();
    }
}
